<!-- pages/role/doctor/home.vue -->
<template>
  <view class="doctor-home">
    <view class="header">
      <text class="title">医生工作台</text>
      <view class="action-buttons">
        <uni-button type="primary" size="mini" @click="navigateToAddPatient">添加患者</uni-button>
        <uni-button type="default" size="mini" @click="navigateToDiagnose">诊断中心</uni-button>
      </view>
    </view>
    
    <view class="search-box">
      <uni-search-bar 
        v-model="searchValue"
        placeholder="搜索患者姓名或电话" 
        radius="100" 
        clearButton="auto"
        cancelButton="none"
      />
    </view>

    <view class="patient-list">
      <view v-if="filteredPatients && filteredPatients.length > 0">
        <view
          v-for="patient in filteredPatients"
          :key="patient.id"
          class="patient-card"
          @click="selectPatient(patient)"
        >
          <view class="left">
            <u-avatar :text="patient.name ? patient.name.charAt(0) : '?'" :size="50"></u-avatar>
          </view>
          <view class="center">
            <view class="name-gender">
              <text class="name">{{ patient.name }}</text>
              <text class="gender-tag">{{ patient.sex === 'male' ? '男' : '女' }}</text>
            </view>
            <view class="info">
              <text>{{ patient.age }}岁</text>
              <text class="dot-divider">•</text>
              <text>{{ patient.bloodType || '未知' }}型血</text>
            </view>
            <view class="phone">
              <u-icon name="phone" size="14"></u-icon>
              <text>{{ patient.phone }}</text>
            </view>
          </view>
          <view class="right">
            <view class="status-tag" :class="getHealthStatusClass(patient)">
              {{ getHealthStatusText(patient) }}
            </view>
            <u-icon name="arrow-right" color="#ccc" size="20"></u-icon>
          </view>
        </view>
      </view>
      
      <u-empty v-else mode="data" text="暂无患者数据"></u-empty>
    </view>
    
    <u-loading-page :loading="loading"></u-loading-page>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { usePatientStore } from '@/store/modules/useDoctorStore';
import { useUserStore } from '@/store/modules/useUserStore';

const patientStore = usePatientStore();
const userStore = useUserStore();
const searchValue = ref('');
const loading = ref(false);

onMounted(async () => {
  // 显示加载提示
  uni.showLoading({
    title: '加载中...'
  });
  
  loading.value = true;
  try {
    console.log('开始获取患者列表...');
    
    // 先清空现有患者列表，避免ID冲突问题
    patientStore.patientList.length = 0;
    
    await patientStore.fetchPatientList();
    console.log('患者列表获取完成，数量:', patientStore.getPatientList.length);
  } catch (error) {
    console.error('获取患者列表失败:', error);
    uni.showToast({
      title: '获取患者列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    // 隐藏加载提示
    uni.hideLoading();
  }
});

// 筛选患者
const filteredPatients = computed(() => {
  const query = searchValue.value.toLowerCase();
  const patients = patientStore.getPatientList;
  
  if (!query) return patients;
  
  return patients.filter(patient => 
    (patient.name && patient.name.toLowerCase().includes(query)) || 
    (patient.phone && patient.phone.includes(query))
  );
});

// 选择患者，跳转到详情页
const selectPatient = (patient) => {
  if (!patient || !patient.id) {
    console.error('无效的患者信息:', patient);
    uni.showToast({
      title: '患者信息无效',
      icon: 'none'
    });
    return;
  }

  console.log('选择患者:', patient.id, patient.name);
  
  // 先设置当前患者ID
  patientStore.setCurPatientId(patient.id).then(() => {
    // 确保ID设置成功后再跳转
    uni.navigateTo({
      url: `/pages/role/doctor/patientDetail?id=${patient.id}`,
      success: () => {
        console.log('跳转成功，患者ID:', patient.id);
      },
      fail: (err) => {
        console.error('跳转失败:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }).catch(err => {
    console.error('设置患者ID失败:', err);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  });
};

// 导航到添加患者页面
const navigateToAddPatient = () => {
  uni.navigateTo({
    url: '/pages/role/doctor/patientAdd'
  });
};

// 导航到诊断中心页面
const navigateToDiagnose = () => {
  uni.navigateTo({
    url: '/pages/role/doctor/diagnose'
  });
};

// 获取健康状态的样式类
const getHealthStatusClass = (patient) => {
  const status = patient.healthStatus || 'normal';
  return {
    'status-normal': status === 'normal',
    'status-warning': status === 'warning',
    'status-danger': status === 'danger'
  };
};

// 获取健康状态文本
const getHealthStatusText = (patient) => {
  const statusMap = {
    'normal': '健康',
    'warning': '注意',
    'danger': '异常'
  };
  return statusMap[patient.healthStatus || 'normal'];
};
</script>

<style lang="scss" scoped>
.doctor-home {
  padding: 30rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
    }
    
    .action-buttons {
      display: flex;
      gap: 20rpx;
    }
  }
  
  .search-box {
    margin-bottom: 30rpx;
  }
  
  .patient-list {
    .patient-card {
      display: flex;
      align-items: center;
      background-color: #ffffff;
      padding: 30rpx;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      
      .left {
        margin-right: 20rpx;
      }
      
      .center {
        flex: 1;
        
        .name-gender {
          margin-bottom: 10rpx;
          display: flex;
          align-items: center;
          
          .name {
            font-size: 32rpx;
            font-weight: bold;
            margin-right: 15rpx;
          }
          
          .gender-tag {
            font-size: 24rpx;
            color: #666;
            background-color: #f2f2f2;
            padding: 2rpx 10rpx;
            border-radius: 4rpx;
          }
        }
        
        .info {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 6rpx;
          
          .dot-divider {
            margin: 0 10rpx;
          }
        }
        
        .phone {
          font-size: 26rpx;
          color: #666;
          display: flex;
          align-items: center;
          
          text {
            margin-left: 8rpx;
          }
        }
      }
      
      .right {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 15rpx;
        
        .status-tag {
          font-size: 24rpx;
          padding: 4rpx 16rpx;
          border-radius: 30rpx;
          
          &.status-normal {
            background-color: #ecf5ff;
            color: #2979ff;
          }
          
          &.status-warning {
            background-color: #fdf6ec;
            color: #ff9900;
          }
          
          &.status-danger {
            background-color: #fef0f0;
            color: #fa3534;
          }
        }
      }
    }
  }
}
</style>
